/**
 * Created by liwei on 17/5/25.
 */

'use strict'
import Vue from 'vue'

var exportTemplete = require('html!./algorithm_set_edit.html')
require('./algorithm.less')

module.exports = {
  template: exportTemplete,
  data: function () {
    return {
      dataList: [],
      dataType: [],
      currentAistList: [],
      fileHead: [],
      fileList: [],
      userId: localStorage.getItem('userId'),
      modelId: '',
      oldModelId: '',
      dataHead: {},
      modelName: '',
      modelPic: '',
      oldTableName: ''
    }
  },
  created: function () {
    this.modelId = this.$route.query.modelId
    this.oldModelId = this.$route.query.oldModelId
    this.modelPic = this.$route.query.modelPic
    this.modelName = this.$route.query.modelName
    this.init()
  },
  mounted: function () {
    this.getAllType()

  },
  methods: {
    init: function () {
      var me = this
      //删除
      $(document).on('click', '.delete', function (e) {
        $(this).parent('div').remove()
      })
      //设置算法参数
      $(document).on('click', '.args-setting', function (e) {
        var aiId = $(this).parent('div').find('input').val()
        console.log(aiId)
        me.aiSet(aiId)
      })

    },
    aiSet: function (aiId) {
      var me = this
      var aiMapid="";
      me.$http.get('/algorithmController/getAlgorithmArgs.do?aiId=' + aiId+"&modelId="+me.modelId)
        .then(function (res) {
          console.log(res)
          if (res.data.code == '000000') {
            $("#aiArgs").html("");
            var temp="";
            aiMapid=res.data.result.id;
            if(aiMapid){
              var args = JSON.parse(res.data.result.aiArgs);
              for(var k in args){
                temp+='<div><span>'+k+'</span><input name="'+k+'" type="text" value="'+args[k]+'"></div>'
              }
            }else{
              // var args = res.data.result.aiArgs.split(",")
              // for (var i=0;i<args.length;i++){
              //   temp+='<div><span>'+args[i]+'</span><input name="'+args[i]+'" type="text"></div>'
              // }
              var args = JSON.parse(res.data.result.aiArgs);
              for(var k in args){
                temp+='<div><span>'+k+'</span><input name="'+k+'" type="text" placeholder="'+args[k]+'"></div>'
              }
            }
            $("#aiArgs").append(temp);
          } else {
            layer.msg('系统繁忙，请稍后再试')
          }
        }.bind(this))
      var lay = layer.open({
        type: 1,
        title: false,
     /*   offset: '120px', //具体配置参考：offset参数项*/
        content: $('#args-add'),
        area: ['500px', '370px'],
        closeBtn: 0,
        shade: 0, //不显示遮罩，
        btn: ['修改', '取消'],
        btn1:function(){
          var aiArgs={};
          var input = $("#aiArgs").find("input");
          for(var i=0;i<input.length;i++){
            var name=$(input[i]).attr("name");
            aiArgs[name]=$(input[i]).val();
          }
          console.log(aiArgs);
          var layLoad = layer.load(2, {shade: 0.1, area: ['32px', '64px']})
          $.ajax({
            url: Vue.prototype.$http.defaults.baseURL + '/algorithmController/doSetAlgorithmArgs.do',
            method: 'post',
            data: {
              'modelId': me.modelId,
              'aiId': aiId,
              'aiArgs': JSON.stringify(aiArgs),
              'aiMapId': aiMapid
            },
            dataType: 'json',
            success: function (res) {
              layer.close(layLoad)
              if (res.code == '000000') {
                localStorage.setItem('modelId', me.modelId)
                layer.closeAll();
              } else {
                layer.msg('系统繁忙，请稍后再试')
              }
            },
            error: function (error) {
              console.error(error, 'error')
            }
          })
        }
      })
    },
    getAllType: function () {
      var me = this
      me.$http.get('/algorithmController/getAlgorithmType.do')
        .then(function (res) {
          me.dataType = []
          if (res.data.code == '000000') {
            console.log(res)
            for (var j = 0; j < res.data.result.length; j++) {
              me.dataType.push(res.data.result[j])
            }
            me.$nextTick(function () {
              var spans = $('#aiTypeTab').find('span')
              $(spans[0]).addClass('active')
              this.getAllData()
            })

          } else {
            layer.msg('系统繁忙，请稍后再试')
          }

        }.bind(this))
    },
    getAllData: function (aiType) {
      var aiName = $('#search').val()
      var aiType = aiType || $('#aiTypeTab').find('.active').attr('value')
      var me = this
      me.$http.get(Vue.prototype.$http.defaults.baseURL + '/algorithmController/getAlgorithmList.do?modelId=' + me.oldModelId + '&aiName=' + aiName + '&aiType=' + aiType)
        .then(function (res) {
          me.dataList = []
          me.currentAistList = []
          if (res.data.code == '000000') {
            console.log(res)
            for (var j = 0; j < res.data.result.list.length; j++) {
              me.dataList.push(res.data.result.list[j])
            }
            for (var j = 0; j < res.data.result.currentAist.length; j++) {
              me.currentAistList.push(res.data.result.currentAist[j])
            }
            me.dataHead = res.data.result[res.data.result.length - 1]
          } else {
            layer.msg('系统繁忙，请稍后再试')
          }

        }.bind(this))
    },
    /**
     * 获取浏览器url参数
     * @param  {String} name 参数值
     *
     */
    getQueryString: function (name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
      var r = window.location.search.substr(1).match(reg)
      if (r != null) return unescape(r[2])
      return null
    },
    /**
     * 添加算法
     */
    add: function (AIId, AIname) {
      var temp = '<div class="selected-item">' +
        '        <span class="pl30">' + AIname + '</span>' +
        '         <span class="args-setting">参数设置</span>' +
        '        <span class="del fr ml10 delete">删除</span>' +
        '        <input type="text" style="display: none" value="' + AIId + '">' +
        '        </div>'
      $('#cleckAi').append(temp)
    },
    /**
     * 查看算法
     */
    look: function (val, name,jj) {
      debugger
      $('#detailsAiName').html(name)
      $('#detailsAiDescribe').html(val)
      $('#AiDescribe').html(jj)
      var lay = layer.open({
        type: 1,
        title: false,
      /*  offset: '120px', //具体配置参考：offset参数项*/
        content: $('#details'),
        area: ['700px', '540px'],
        closeBtn: 0/*,
        shade: 0 //不显示遮罩*/
      })
    },
    /**
     * 算法类型tab
     */
    queryByType: function (event) {
      var me = this
      console.log(event)
      var span = event.currentTarget
      console.log(span)
      var aiType = $(span).attr('value')
      $(span).parent('div').find('span').removeClass('active')
      $(span).addClass('active')
      me.getAllData(aiType)
    },
    goBack: function () {
      var me = this
      me.$router.push({path: '/product/editModelBasic', query: {modelId: me.modelId}})
    },
    /**
     * 关闭layer
     */
    closelayer:function () {
      layer.closeAll();
    },
    /**
     * 下一步
     */
    submit: function () {
      var me = this
      var AIids = $('#cleckAi').find('input')
      var AIidsStr = ''
      if($(AIids).length<=0){
        layer.msg('请选择算法');
        return;
      }
      var layLoad = layer.load(2, {shade: 0.1, area: ['32px', '64px']});
      for (var i = 0; i < $(AIids).length; i++) {
        AIidsStr += $(AIids[i]).val() + ','
      }
      console.log(AIidsStr)

      $.ajax({
        url: Vue.prototype.$http.defaults.baseURL + '/algorithmController/addAlgorithm2model.do',
        method: 'post',
        data: {
          'modelId': me.modelId,
          'AIId': AIidsStr
        },
        dataType: 'json',
        success: function (res) {
          layer.close(layLoad)
          if (res.code == '000000') {
            localStorage.setItem('modelId', me.modelId)
            // me.$router.push('/product/modelImportData')
            me.$router.push({path: '/product/modelImportDataEdit', query: {modelId: me.modelId,oldModelId:me.modelId}})
          } else {
            layer.msg('系统繁忙，请稍后再试')
          }
        },
        error: function (error) {
          console.error(error, 'error')
        }
      })
    }
  }
}
